package example.conc;

/**
 * zhu.tan@gmail.com
 * 05-Jan-2010
 */
public class ProducerConsumer {
    static int THREADS = 10;

    public static void main(String[] args) {
        Consumer[] consumers = new Consumer[THREADS];
        Producer[] producers = new Producer[THREADS];
        ConditionalVariableEx data = new ConditionalVariableEx();
        Thread[] threads = new Thread[THREADS * 2];
        for (int i = 0; i < THREADS; i++) {
            consumers[i] = new Consumer(data);
            producers[i] = new Producer(data);
            threads[i] = new Thread(consumers[i], "" + i);
            threads[i + THREADS] = new Thread(producers[i], "" + i);
        }

        for (int i = 0; i < THREADS * 2; i++) {
            threads[i].start();
        }

        for (int i = 0; i < THREADS * 2; i++) {
            try {
                threads[i].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Producer implements Runnable {
    ConditionalVariableEx myData;

    public Producer(ConditionalVariableEx myData) {
        super();
        this.myData = myData;
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
            myData.put(Thread.currentThread().getName() + " : " + i);
        }
    }
}

class Consumer implements Runnable {
    ConditionalVariableEx myData;

    public void run() {
        for (int i = 0; i < 10; i++) {
            myData.get();
        }
    }

    Consumer(ConditionalVariableEx myData) {
        super();
        this.myData = myData;
    }
}

